<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>getSnapshotBeforeUpdate的使用场景</title>
</head>
<style>
  .list {
    width: 300px;
    height: 150px;
    background-color: pink;
    overflow: auto;
  }

  .news {
    height: 30px;
  }
</style>
<body>
  <div id="test"></div>

  <script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://cdn.staticfile.org/prop-types/15.6.1/prop-types.js"></script>

  <script type="text/babel">
    class NewsList extends React.Component {
      state = { newsArr: [] }

      componentDidMount() {
        setInterval(() => {
          const { newsArr } = this.state
          // 模拟一条新闻
          const news = '新闻'+(newsArr.length+1)
          // 更新状态
          this.setState({newsArr: [news, ...newsArr]})
        }, 1000)
      }

      getSnapshotBeforeUpdate() {
        console.log(this.list)
        // 拿到更新前的高度
        return this.list.scrollHeight
      }

      componentDidUpdate(preProps, preState, snapshotValue) {
        console.log(snapshotValue)
        this.list.scrollTop += this.list.scrollHeight - snapshotValue
      }

      render() {
        return (
          <div className="list" ref={(currentNode) => this.list = currentNode}>
            {
              this.state.newsArr.map((n, index) => {
                return <div className="news" key={index} >{n}</div>
              })
            }            
          </div>
        )
      }
    }
    ReactDOM.render(<NewsList/>, document.getElementById('test'))
  </script>
</body>
</html>